import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

import { useUserStore } from '@/store'
import { authGuard, authRoutes, removeAuthRoutes } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import staticRoutes from '@/router/staticRoutes'
import dynamicRoutes from '@/router/dynamicRoutes'
import userMock from '@/mock/user'

// 所有路由
export const allRoutes = staticRoutes.concat(dynamicRoutes)

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: import.meta.env.VITE_AUTH_MODE === 'static' ? allRoutes : staticRoutes
})



// initRoutes 是一个初始化路由标识（动态权限验证方式会用到）
let initRoutes = false
router.beforeResolve(async (to, from, next) => {
  const userStore = useUserStore()

  if ((!userStore.data || !userStore.data.token) && to.path !== '/login') {
    return next({ path: '/login' })
  }

  if (!userStore.staticRoutes || userStore.staticRoutes.length === 0 || userStore.staticRoutes.length !== router.options.routes.length) {
    userStore.staticRoutes = router.options.routes
  }

  if (import.meta.env.VITE_AUTH_MODE === 'static') {
    if (!authGuard(to, userStore.roles) && to.path !== '/login') {
      ElMessage.error('没有权限！')
      if (userStore.lastRoute && userStore.lastRoute.name) {
        return next({ name: userStore.lastRoute.name })
      } else {
        return next({ name: from.name })
      }
    }
    userStore.lastRoute = to
    return next()
  }

  if (import.meta.env.VITE_AUTH_MODE === 'dynamic') {
    if (to.path === '/login') {
      initRoutes = false
    }
    if (!initRoutes && from.path === '/login') {
      initRoutes = true

      try {
        await userStore.initDynamicRoutes()  // 异步初始化动态路由
        if (userStore.hasDynamicRoutes) {
          removeAuthRoutes(userStore.dynamicRoutes, router)
        }
        authRoutes(userStore.dynamicRoutes, router)
        router.replace(to.path)
      } catch (error) {
        console.error('初始化动态路由失败', error)
      }
      return
    }

    if (!initRoutes && !userStore.hasDynamicRoutes && userStore.data && userStore.data.token && from.path !== '/login' && to.path !== '/login') {
      initRoutes = true

      try {
        const res = await userMock.getAuths(userStore.data.token)
        if (res.data.auths) {
          userStore.auths = res.data.auths
          await userStore.initDynamicRoutes()
          authRoutes(userStore.dynamicRoutes, router)
          router.replace(to.path)
        }
      } catch (error) {
        console.error('获取权限信息失败', error)
      }
      return
    }

    if (!userStore.hasDynamicRoutes && from.path !== '/login' && to.path !== '/login') {
      return next('/login')
    }
  }

  // 如果以上条件都不符合，继续导航
  next()
})

export default router
